package com.cloud.lawcase.common.openapi;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.lawcase.api.entity.TcAccessToken;
import com.cloud.lawcase.api.mapper.TcAccessTokenMapper;
import com.cloud.lawcase.api.service.LawApiManagerService;
import com.cloud.lawcase.common.result.Quokka;
import com.cloud.lawcase.common.utils.DateHelper;
import com.cloud.lawcase.common.utils.JwtTokenHelper;

@Aspect
@Component
public class OpenApiAuthorityAspect {

	@Autowired
	private TcAccessTokenMapper tcAccessTokenMapper;
	@Autowired
	public LawApiManagerService lawApiManagerService;

	@Around(value = "execution(* com.cloud.lawcase.api.web.OpenApiController.list*(..))")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

		Object[] args = joinPoint.getArgs();
		HttpServletRequest request = (HttpServletRequest) args[0];
		
		String authorizationHeader = request.getHeader("Authorization");
		if (StringUtils.isEmpty(authorizationHeader)) {
			Quokka quokka = new Quokka(false);
			quokka.setMessage("未认证的请求");
			return quokka;
		}
		// 获取过期时间，检查是否过期
		String appId = null;
		try {
			appId = JwtTokenHelper.parserClaims(authorizationHeader);
		} catch (Exception e) {
			Quokka quokka = new Quokka(false);
			quokka.setMessage("无效的Token");
			return quokka;
		}
		// 权限验证
		String requestURI = request.getRequestURI();
		if (requestURI.indexOf("refreshtoken") == -1) {
			boolean hasAuthority = lawApiManagerService.checkUrlAuthority(appId, requestURI);
			if (!hasAuthority) {
				Quokka quokka = new Quokka(false);
				quokka.setMessage("对不起，您没有访问这个接口的权限");
				return quokka;
			}
		}
		//为第二个参数设置APPID值
		request.setAttribute("appId", appId);
		Quokka returnVal = (Quokka) joinPoint.proceed();
		// 对将要过期的请求添加超期提醒
		TcAccessToken accessToken = tcAccessTokenMapper.selectByPrimaryKey(appId);
		Date now = new Date();
		if (now.after(
				DateHelper.getDateBeforeOrAfterDays(accessToken.getOverdueDate(), -accessToken.getOverdueRemind()))) {
			returnVal.setMessage("您的接口权限即将到期，请及时续费");
		}
		return returnVal;
	}
}
